#ifndef __FD_MANAGER_H__
#define __FD_MANAGER_H__

#include<memory>
#include<vector>
#include"thread.h"
#include"singleton.h"

namespace sylar{
//每一个句柄的信息
class FdCtx: public std::enable_shared_from_this<FdCtx>{
	public:
		typedef std::shared_ptr<FdCtx> ptr;
		FdCtx(int fd);
		~FdCtx();
		bool isInit()const { return m_isInit;}
		bool isSocket()const {return m_isSocket;}
		bool isClose()const {return m_isClosed;}
		
		void setUserNonblock(bool v){m_userNonblock = v;}
		bool getUserNonblock()const {return m_userNonblock;}

		void setSysNonblock(bool v){m_sysNonblock = v;}
		bool getSysNonblock()const {return m_sysNonblock;}

		//只设置一种超时函数，通过类型区分是读超时还是写超时
		void setTimeout(int type,uint64_t v);
		uint64_t getTimeout(int type);
	private:
		bool init();

	private:
		//位域，设置一个bit
		bool m_isInit: 1;       //是否初始化
		bool m_isSocket: 1;     // 是否socket
		bool m_sysNonblock: 1;  // 是否非阻塞
		bool m_userNonblock: 1;
		bool m_isClosed: 1;
		int m_fd;
		uint64_t m_recvTimeout;
		uint64_t m_sendTimeout;
};

//管理所有的句柄
class FdManager{
	public:
		typedef RWMutex RWMutexType;
		FdManager();

		//如果查询不存在且auto_create=true, 则创建并返回
		FdCtx::ptr get(int fd,bool auto_create = false);
		void del(int fd);

	private:
		RWMutexType m_mutex;
		std::vector<FdCtx::ptr> m_datas;
};

typedef Singleton<FdManager> FdMgr;	
}
#endif